import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:leader_doctor_flutter/common/data/app.dart';
import 'package:leader_doctor_flutter/common/http/api.dart';
import 'package:leader_doctor_flutter/common/http/http_client.dart';
import 'package:leader_doctor_flutter/common/utils/string_utils.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/common/widget/refresh_custom_widget.dart';
import 'package:leader_doctor_flutter/common/widget/table_placeholder_widget.dart';
import 'package:leader_doctor_flutter/model/withdraw_record_list.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

// 顶部筛选分类模型
class TopFilterCategoryItemModel {
  String title;
  String timeType;

  TopFilterCategoryItemModel({required this.title, required this.timeType});
}

class WalletWithdrawalRecordPage extends StatefulWidget {
  const WalletWithdrawalRecordPage({super.key});

  @override
  State<WalletWithdrawalRecordPage> createState() => _WalletWithdrawalRecordPageState();
}

class _WalletWithdrawalRecordPageState extends State<WalletWithdrawalRecordPage> {
  final List<TopFilterCategoryItemModel> topFilterItems = [
    TopFilterCategoryItemModel(title: "全部", timeType: ""),
    TopFilterCategoryItemModel(title: "本月", timeType: "month"),
    TopFilterCategoryItemModel(title: "本年", timeType: "year"),
  ];

  int selectedButtonIndex = 0; // 默认选择的按钮坐标
  var pageSize = 20;
  var pageNo = 1;
  var selectStatus = ""; // 页面顶部筛选时间分类
  bool dataLoaded = false; // 数据请求中

  final RefreshController _refreshController = RefreshController(initialRefresh: false);

  void _onRefresh() async {
    pageNo = 1;
    _getWithdrawRecordList(selectStatus);
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    pageNo++;
    _getWithdrawRecordList(selectStatus);
    _refreshController.loadComplete();
  }

  @override
  void initState() {
    super.initState();
    _getWithdrawRecordList(selectStatus);
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  List<WithdrawRecordListModel> detailsList = [];

  @override
  Widget build(BuildContext context) {
    return contentView();
  }

  Widget contentView() {
    return Scaffold(
      appBar: CommWidget.getCommAppbar(context),
      body: Container(
        color: const Color(0xFFF6F6F6),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Container(
            height: 60.w,
            color: ColorRes.white,
            child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: List.generate(
                    topFilterItems.length,
                    (index) => Padding(
                        padding: EdgeInsets.symmetric(horizontal: 10.w),
                        child: TopTimeButton(
                            title: topFilterItems[index].title,
                            timeType: topFilterItems[index].timeType,
                            isSelected: selectedButtonIndex == index,
                            onPressed: () {
                              pageNo = 1;
                              selectStatus = topFilterItems[index].timeType;
                              _getWithdrawRecordList(topFilterItems[index].timeType);
                              setState(() {
                                selectedButtonIndex = index;
                              });
                            })))),
          ),
          Expanded(
            child: Container(
              color: const Color(0xFFF6F6F6),
              child: SmartRefresher(
                controller: _refreshController,
                enablePullDown: true,
                enablePullUp: true,
                onRefresh: _onRefresh,
                onLoading: _onLoading,
                child: dataLoaded
                    ? (detailsList.isEmpty
                        ? TablePlaceholderWidget(
                            message: "暂无数据",
                            yOffset: -30,
                          ) // 显示占位图
                        : ListView.builder(
                            shrinkWrap: true,
                            itemCount: detailsList.length,
                            itemBuilder: (context, index) {
                              return DetailsListCell(detailsList[index]);
                            },
                          ))
                    : TablePlaceholderWidget(
                        message: "暂无数据",
                        yOffset: -30,
                      ),
              ),
            ),
          ),
        ]),
      ),
    );
  }

  /// 获取提现历史记录
  _getWithdrawRecordList(String time) async {
    var user = App.instance.userInfo;
    var httpRequest = HttpRequest(Api.getWithdrawRecordList, body: {
      'userId': user?.id,
      'userType': "",
      'startTime': "",
      'endTime': "",
      'timeType': time,
      "pageIndex": pageNo.toString(),
      "pageSize": pageSize.toString()
    });
    var httpResponse = await HttpClient.postJson(httpRequest);
    var map = jsonDecode(utf8.decode(httpResponse.raw!.bodyBytes));
    var tmpList = ((map['responseBody'] as List?) ?? []).map((e) => WithdrawRecordListModel.fromJson(e)).toList();
    if (tmpList.length < pageSize) {
      _refreshController.loadNoData();
    } else {
      _refreshController.loadComplete();
    }
    pageNo == 1 ? detailsList = tmpList : detailsList.addAll(tmpList);
    setState(() {
      dataLoaded = true;
    });
  }
}

// 顶部时间筛选
class TopTimeButton extends StatelessWidget {
  final String title;
  final String timeType;
  final bool isSelected;
  final VoidCallback onPressed;

  TopTimeButton({
    required this.title,
    required this.timeType,
    required this.isSelected,
    required this.onPressed,
  });

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(
        backgroundColor: isSelected ? ColorRes.colorMain : ColorRes.colore6e6ff,
        minimumSize: const Size(65, 30),
      ),
      onPressed: onPressed,
      child: Text(
        title,
        style: TextStyle(color: isSelected ? ColorRes.white : ColorRes.colorMain, fontSize: 15.sp),
      ),
    );
  }
}

// 提现记录列表
class DetailsListCell extends StatelessWidget {
  List titleList = [
    "银行卡号",
    "开户行",
    "提现金额",
    "到账金额",
    "订单号",
  ];

  final WithdrawRecordListModel listmodel;

  DetailsListCell(this.listmodel);

  @override
  Widget build(BuildContext context) {
    List descList = [
      listmodel.cardNo,
      listmodel.bankName,
      "¥${listmodel.totalFee}",
      "¥${listmodel.pay}",
      listmodel.yzhOrderId
    ];

    String statusText;
    Color statusColor;

// 根据状态值设置翻译和颜色
    if (listmodel.status == "1") {
      statusText = "提现成功";
      statusColor = Color(0xFF00E3BD);
    } else if (listmodel.status == "2") {
      statusText = "提现失败";
      statusColor = Color(0xFFFF7275);
    } else if (listmodel.status == "15") {
      statusText = "取消";
      statusColor = Color(0xFFFF7275);
    } else if (listmodel.status == "4" || StringUtils.isEmpty(listmodel.status)) {
      statusText = "处理中";
      statusColor = Color(0xFFFFB50C);
    } else {
      statusText = "未知状态";
      statusColor = Colors.black;
    }

    return Padding(
      // padding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 13.w),
      padding: EdgeInsets.fromLTRB(15.w, 12.w, 15.w, 0.w),
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(6.0),
          color: Colors.white,
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: EdgeInsets.symmetric(
                horizontal: 15.w,
                vertical: 15.w,
              ),
              child: Row(
                children: [
                  Text(
                    '${listmodel.createTime}', // 列表时间数据
                    style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16.sp, color: Color(0xFF333333)),
                  ),
                  Spacer(),
                  Text(
                    '${statusText}', // 列表状态数据
                    style: TextStyle(
                      color: statusColor,
                      fontSize: 14.sp,
                    ),
                  ),
                ],
              ),
            ),
            Container(
              margin: EdgeInsets.symmetric(
                horizontal: 15.0,
              ),
              height: 1.w,
              color: Color(0xFFF2F2F2),
            ),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: List.generate(
                titleList.length,
                (rowIndex) => Column(
                  children: [
                    Container(
                      height: 50.w,
                      padding: EdgeInsets.symmetric(
                        horizontal: 15.w,
                      ),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Text(
                            '${titleList[rowIndex]}',
                            style: TextStyle(color: Color(0xFF666666), fontWeight: FontWeight.normal, fontSize: 14.sp),
                          ),
                          SizedBox(width: 15.w),
                          Expanded(
                            child: Align(
                              alignment: Alignment.centerRight,
                              child: Text(
                                '${descList[rowIndex]}',
                                style: TextStyle(
                                  color: Color(0xFF333333),
                                  fontSize: 14.sp,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    if (rowIndex < (descList.length - 1)) // 最后一行不展示行分割线
                      Container(
                        margin: EdgeInsets.symmetric(
                          horizontal: 15.w,
                        ),
                        height: 1.w,
                        color: Color(0xFFF2F2F2),
                      ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
